<template>
  <!-- 冷铁需求详情表单弹窗 -->
  <el-dialog
    v-model="visibleDialog"
    :title="props.title"
    width="65%"
    draggable
    @close="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :inline="true"
      :rules="rules"
      label-width="80"
    >
      <el-row>
        <el-col :span="6">
          <el-form-item label="日期" prop="planActualDate">
            <el-date-picker
              v-model="formData.planActualDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-form-item label="">
            <el-button type="primary" @click="getPlanWorkingForm"
              >查询</el-button
            >
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="班组" prop="crewId">
            <el-select
              v-model="formData.crewId"
              placeholder="请选择班组"
              @change="changeCrew"
              clearable
            >
              <el-option
                v-for="item in crewList"
                :key="item.id"
                :label="item.crewName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-card shadow="never" class="table-container">
        <div class="formTable2">
          <el-table
            max-height="710"
            :data="formData.details"
            :key="Math.random"
            border
            style="width: 100%"
          >
            <el-table-column
              type="index"
              label="序号"
              align="center"
              width="80"
            />
            <el-table-column
              label="计划编号"
              prop="processingOrderNumber"
              min-width="180"
              show-overflow-tooltip
            />
            <el-table-column
              label="产品图号"
              prop="figureNumber"
              min-width="170"
              show-overflow-tooltip
            />
            <el-table-column
              label="产品名称"
              prop="materialName"
              min-width="180"
              show-overflow-tooltip
            >
              <template #default="scope">
                {{ scope.row.materialName }}
              </template>
            </el-table-column>
            <!--<el-table-column
              label="生产日计划号"
              prop="producePlanCode"
              min-width="120"
              show-overflow-tooltip
            />-->
            <el-table-column label="计划人员" props="planUsers" min-width="310">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.planUserIds'"
                  :rules="rules.sonplanUserIds"
                  label-width="0"
                  style="width: 100%"
                >
                  <el-select
                    v-model="row.memberIds"
                    placeholder="请选择计划人员"
                    style="width: 100%"
                    @change="changePlanUser(row)"
                    filterable
                    multiple
                  >
                    <el-option
                      v-for="item in memberList"
                      :key="item.id"
                      :label="`${item.memberName}`"
                      :value="item.memberId"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="生产批次号"
              prop="plannedBatch"
              min-width="100"
              show-overflow-tooltip
            />
            <el-table-column
              label="生产日期"
              prop="planActualDate"
              min-width="100"
              show-overflow-tooltip
              align="center"
              :formatter="formatDate"
            />
            <el-table-column
              label="模数"
              prop="pm"
              min-width="80"
              show-overflow-tooltip
              header-align="center"
              align="right"
              v-if="props.isPm"
            />
            <el-table-column
              label="计划包"
              prop="mpackage"
              min-width="80"
              show-overflow-tooltip
              header-align="center"
              align="right"
              v-if="!props.isReadonly"
            />
            <el-table-column
              label="计划炉"
              prop="mfurnace"
              min-width="100"
              show-overflow-tooltip
              header-align="center"
              align="center"
              v-if="!props.isReadonly && !props.isPm"
            >
              <template #default="scope">
                <span v-if="scope.row.mfurnace == 0.5">半炉</span>
                <span v-else-if="scope.row.mfurnace == 1">一炉</span>
              </template>
            </el-table-column>
            <el-table-column
              label="计划数量"
              prop="planQuantity"
              min-width="100"
              show-overflow-tooltip
              header-align="center"
              align="right"
              v-if="props.isReadonly"
            />
            <el-table-column
              label="计划开始时间"
              prop="planBeginTime"
              min-width="160"
              show-overflow-tooltip
              align="center"
            />
            <el-table-column
              label="计划结束时间"
              prop="planEndTime"
              min-width="160"
              show-overflow-tooltip
              align="center"
            />
          </el-table>
        </div>
      </el-card>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          type="primary"
          :loading="loading"
          v-if="formData.details.length > 0"
          @click="handleSubmit"
          >保 存</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "USERASSIGN",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  isPm: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  sonplanUserIds: [
    { required: true, message: "请输入计划人员", trigger: "change" },
  ],
});

function validateDegree(rule: any, value: any, callback: (a?: any) => {}) {
  if (isNaN(parseFloat(value)) && isFinite(value)) {
    callback(new Error("请输入整数"));
  } else if (!/^[+-]?\d+?(e[+-]?\d+)?$/.test(value)) {
    callback(new Error("请输入整数"));
  } else if (Number(value) < 0) {
    callback(new Error("请输入大于0的整数"));
  } else {
    callback();
  }
}
const formRef = ref(ElForm);

let formData = reactive({
  details: [],
  crewId: "",
  crewName: "",
  planActualDate: getCurrentDate(),
});

watch(
  () => props.data,
  (newVal: any) => {
    // const { details } = newVal;
    // formData.details = details;
    // // Object.assign(formData, {
    // //   details,
    // // });
    // if (details?.length > 0) {
    //   getCrews();
    //   formData.details.forEach((item) => {
    //     if (item.planUserIds) {
    //       item.memberIds = item.planUserIds.split(",");
    //     }
    //   });
    //   if (details[0].crewId) {
    //     formData.crewId = details[0].crewId;
    //     getCrewMembers();
    //   }
    // }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [];
  formData.crewId = "";
  formData.crewName = "";
  memberList.value = [];
}

const loading = ref(false);

function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = "人员指派";
      await request({
        url: "/mes/mesplanworkingform/userAssign",
        method: "post",
        data: formData.details,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

//时间格式处理，yyyy-mm-dd
function formatDate(row, column) {
  const date = row[column.property];
  if (!date) return "";
  return date.split(" ")[0]; // 返回日期的年月日部分，而隐藏时间部分
}
const crewList = ref([]);
async function getCrews() {
  await request({
    url: "mes/mescrew/getCrew",
    method: "post",
    data: {
      plantId: formData.plantId,
      enabled: 1,
    },
  }).then((res) => {
    crewList.value = res.data;
  });
}
function changeCrew(val) {
  formData.crewId = val;
  formData.crewName = "";
  memberList.value = [];
  formData.details.forEach((item) => {
    item.planUserIds = "";
    item.planUsers = "";
    item.memberIds = [];
  });
  if (val) {
    let crew = crewList.value.find((item) => item.id == val);
    formData.crewName = crew.crewName;
    getCrewMembers();
  }
}
//人员
const memberList = ref([]);
async function getCrewMembers() {
  await request({
    url: "mes/mescrew/getCrewMembers",
    method: "post",
    data: {
      id: formData.crewId,
    },
  }).then((res) => {
    memberList.value = res.data;
  });
}
//人员
const changePlanUser = (row: any) => {
  row.planUserIds = row.memberIds.join(",");
  let materialNameList = [];
  row.memberIds.forEach((item: any) => {
    memberList.value.forEach((i) => {
      if (item === i.memberId) {
        materialNameList.push(i.memberName);
      }
    });
  });
  row.planUsers = materialNameList.join(",");
};
// 获取当前日期yyyymmdd
function getCurrentDate() {
  const today = new Date();
  let year = today.getFullYear();
  let month = (today.getMonth() + 1).toString().padStart(2, "0");
  let day = today.getDate().toString().padStart(2, "0");
  return year.toString() + "-" + month + "-" + day;
}
async function getList() {
  request({
    url: `/mes/mesplanworkingform/queryByList`,
    method: "post",
    data: {
      planActualDate: formData.planActualDate,
      processesClassification: 3,
    },
  })
    .then((res) => {
      userAssignDialog.data = { details: res.data };
      userAssignDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}
async function getPlanWorkingForm() {
  if (!formData.planActualDate) {
    ElMessage.error("请选择日期");
    return;
  }
  request({
    url: `/mes/mesplanworkingform/queryByList`,
    method: "post",
    data: {
      planActualDate: formData.planActualDate,
      processesClassification: props.data.processesClassification,
    },
  })
    .then((res) => {
      formData.details = res.data;
      if (formData.details.length > 0) {
        getCrews();
        formData.details.forEach((item) => {
          if (item.planUserIds) {
            item.memberIds = item.planUserIds.split(",");
          } else {
            item.memberIds = [];
          }
        });
        if (formData.details[0].crewId) {
          formData.crewId = formData.details[0].crewId;
          getCrewMembers();
        }
      }
    })
    .catch((res) => {
      console.log(res);
    });
  formRef.value.clearValidate();
}
</script>
